//
//  JGComposeController.swift
//  JGWB
//
//  Created by 付建国 on 2016/10/18.
//  Copyright © 2016年 sher. All rights reserved.
//

import UIKit

class JGComposeController: UIViewController {
    
    fileprivate lazy var titleView : ComposeTitleView = ComposeTitleView()
    fileprivate lazy var images : [UIImage] = [UIImage]()
    fileprivate lazy var emoticonVC : EmoticonController = EmoticonController.init {[weak self] (emoticon) in
        self?.textView.insertEmoticon(emoticon: emoticon)
    }
    
    @IBOutlet weak var picPickerView: PicKerCollectionView!
    @IBOutlet weak var textView: ComposeTextView!

    @IBOutlet weak var toolBarBottomCons: NSLayoutConstraint!
    
    @IBOutlet weak var pickerViewBottomons: NSLayoutConstraint!
    override func viewDidLoad() {
        super.viewDidLoad()

        //设置导航栏
        setupNavgationBar()
        
        //添加监听
        setupNotifications()
        
        
        
        
    }
    
    override func viewDidAppear(_ animated: Bool) {
        
        textView.becomeFirstResponder()
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }

}

// MARK:- 设置UI
extension JGComposeController{
    fileprivate func setupNavgationBar(){
        
        navigationItem.leftBarButtonItem = UIBarButtonItem.init(title: "关闭", style: .plain, target: self, action: #selector(closeItemClick))
        
        navigationItem.rightBarButtonItem = UIBarButtonItem.init(title: "发送", style: .plain, target: self, action: #selector(sendItemClick))
        navigationItem.rightBarButtonItem?.isEnabled = false
        
        titleView.frame = CGRect.init(x: 0, y: 0, width: 200, height: 40)
        navigationItem.titleView = titleView
    }
    
    fileprivate func setupNotifications(){
        //监听键盘弹出
        NotificationCenter.default.addObserver(self, selector: #selector(KeyboardWillChangeFrame(note:)), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
        //监听添加照片按钮点击
        NotificationCenter.default.addObserver(self, selector: #selector(addPhotoClick), name: NSNotification.Name(rawValue: PicPickerAddPhotoNote), object: nil)
        //监听删除照片按钮点击
        NotificationCenter.default.addObserver(self, selector: #selector(DeletePhotoClick(note:)), name: NSNotification.Name(rawValue: PicPickerDeletePhotoNote), object: nil)
    }
}

// MARK:- 事件监听
extension JGComposeController{
    @objc fileprivate func closeItemClick(){
        dismiss(animated: true, completion: nil)
    }
    
    @objc fileprivate func sendItemClick(){
        print(self.textView.getEmoticonString())
    }
    
    @objc fileprivate func KeyboardWillChangeFrame(note : Notification){
        
        let duration = note.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! TimeInterval
        let endFrame = (note.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
        let y = endFrame.origin.y
        
        let margin = UIScreen.main.bounds.height - y
        
        toolBarBottomCons.constant = margin
        UIView.animate(withDuration: duration) { 
            self.view.layoutIfNeeded()
        }
    }
    @IBAction func picPickerClick(_ sender: AnyObject) {
        textView.resignFirstResponder()
        
        pickerViewBottomons.constant = UIScreen.main.bounds.height * 0.65 + 44
        UIView.animate(withDuration: 0.5) {
            self.view.layoutIfNeeded()
        }
    }
    @IBAction func emoticonBtnClick(_ sender: AnyObject) {
        //退出键盘
        textView.resignFirstResponder()
        //切换键盘
        textView.inputView = textView.inputView != nil ? nil : emoticonVC.view
        //弹出键盘
        textView.becomeFirstResponder()
    }

}

// MARK:- 添加照片和删除照片事件
extension JGComposeController{
    @objc fileprivate func addPhotoClick(){
        //判断照片源是否可用
        if !UIImagePickerController.isSourceTypeAvailable(.photoLibrary){
            
            return
        }
        //创建照片选择控制器
        let ipc = UIImagePickerController()
        //设置照片源
        ipc.sourceType = .photoLibrary
        //设置代理
        ipc.delegate = self
        //弹出控制器
        present(ipc, animated: true, completion: nil)

    }
    @objc fileprivate func DeletePhotoClick(note : Notification){
        
        guard let image = note.object as? UIImage else{
            return
        }
        guard let index = images.index(of: image) else{
            return
        }
        images.remove(at: index)
        
        picPickerView.images = images
    }
}

// MARK:- UIImagePickerDelegate
extension JGComposeController : UIImagePickerControllerDelegate, UINavigationControllerDelegate{
    
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        //获取选中的照片
        let image = info["UIImagePickerControllerOriginalImage"] as! UIImage
        //展示照片
        images.append(image)
        //将数组赋值给collectionview
        picPickerView.images = images
        //退出控制器
        picker.dismiss(animated: true, completion: nil)
    }
    
}

extension JGComposeController : UITextViewDelegate{
    
    func textViewDidChange(_ textView: UITextView) {
        self.textView.placeHolderLabel.isHidden = textView.hasText
        navigationItem.rightBarButtonItem?.isEnabled = textView.hasText
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        textView.resignFirstResponder()
    }
}



